package com.yxwl.demo.ui.print.printer;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;

import com.print.base.bean.ImgData;
import com.print.base.bean.PrinterConstantPool;
import com.print.base.bean.TaskCallBean;
import com.print.base.listen.TaskCallback;
import com.print.base.utils.SDKUtils;
import com.print.printer.Command;
import com.print.printer.PrintImgHelper;
import com.print.printer.Printer;
import com.yxwl.demo.R;
import com.yxwl.demo.bean.ImgBean;
import com.yxwl.demo.ui.print.PrintActivity;
import com.yxwl.demo.utils.StringUtil;
import com.yxwl.demo.widget.CustomProgress;
import com.yxwl.demo.widget.LogView;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public abstract class PrintImgUtil {
    protected PrintImgHelper helper;
    protected Printer printer;
    protected List<String> list;

    public int density = 8;//打印浓度
    public float speed = 4;//打印速度
    public int threshold = 128;//阈值
    public int paperType = PrinterConstantPool.PaperType.BLACK;//纸张类型
    public int dpi = 8;//分辨率


    public List<ImgBean> imgBeans = new ArrayList<>();
    //纸张大小 单位MM
    public int paperW = 200;
    public int paperH= 270;
    public int count = 1;//打印张数
    //偏移
    public int X;
    public int Y;

    protected int all;





    public PrintImgUtil(Printer printer) {
        helper = printer.getHelper();
        this.printer = printer;

        InputStream is = SDKUtils.getContext().getResources().openRawResource(R.raw.a3);
        BitmapDrawable bmpDraw = new BitmapDrawable(is);
        Bitmap bitmap = bmpDraw.getBitmap();
        for (int i = 0; i < 1; i++) {
            ImgBean bean = new ImgBean("name"+i,zoomImg(bitmap,200*8,300*8));
            imgBeans.add(bean);
        }
    }
    public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        return Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
    }

    public void print(Activity activity) {
        if (!printer.isConnect()) {
            return;
        }

        if (imgBeans.size() == 0) {
            return;
        }


        //初始化要打印的数据
        List<ImgData> datas = new ArrayList<>();
        for (ImgBean bean : imgBeans) {
            ImgData task = new ImgData(bean.getName(), bean.getBitmap(), X, Y);
            datas.add(task);
        }
        //预处理所有图片数据
        helper.setImgDatas(threshold,0, paperW*dpi, paperH*dpi, datas);
        initNames();

        LogView.log("正在打印第1张图片");
        CustomProgress.showPD(activity, "正在打印第1张图片");
        getPrinterStatus();
    }

    private void initNames() {
        list = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            for (ImgBean bean : imgBeans) {
                list.add(bean.getName());
            }
        }
        all = list.size();
        count = 1;
    }


    protected void getPrinterStatus() {
        printer.addTask(Command.get_status(), null, false, statusCall);
    }


    protected boolean check() {
        if (!printer.isConnect()) {
            return true;
        }
        return list == null || list.size() == 0;
    }

    protected void stopPrint() {
        count = -1;
        all = 0;
        helper.stopPrint();
        CustomProgress.dismissPD();
    }

    TaskCallback statusCall = new TaskCallback() {
        @Override
        public void sendStatus(TaskCallBean bean) {
            if (bean.status != PrinterConstantPool.Status.OK) {
                LogView.log("发送失败,自动结束打印 " + bean.msg);
                CustomProgress.dismissPD();
            }
        }

        @Override
        public void readCall(TaskCallBean bean) {
            if (bean.data == null) {
                return;
            }
            print(bean);
        }

        @Override
        public int timeOut() {
            return 2000;
        }
    };

    protected boolean print(TaskCallBean bean){
        String s = printer.data2Str(bean);
        if (bean.data!=null){
            LogView.log("读取打印机状态 >> type: " + bean.type + ", msg: " + bean.msg + ", hex: " + StringUtil.bytetToHex(bean.data)+ ", data: " + new String(bean.data));
        }
        if (s == null || !s.equals("0")) {
            LogView.log("打印结束，打印机状态异常： " + s);
            stopPrint();
            return true;
        }
        return false;
    }


    TaskCallback printCall = new TaskCallback() {
        @Override
        public void sendStatus(TaskCallBean bean) {
            if (bean.status != PrinterConstantPool.Status.OK) {
                LogView.log("发送失败,自动结束打印 " + bean.msg);
                CustomProgress.dismissPD();
            }
        }

        @Override
        public void readCall(TaskCallBean bean) {
            try {
                LogView.log("读取打印回调>> type: " + bean.type + ", msg: " + bean.msg + ", hex: " + StringUtil.bytetToHex(bean.data)+ ", data: " + new String(bean.data));
            } catch (Exception ignored) {
            }
            printReadCall(bean);
        }

        @Override
        public int timeOut() {
            return Math.max(paperH *dpi * 30, 10000);//根据图片高度来配置等待耗时
        }
    };

    protected void printReadCall(TaskCallBean bean){}
}
